import './index.scss'

import {Row,Col,Typography,Tabs,Form,Button,Checkbox,Input, message} from "antd"
import { useEffect, useRef, useState } from 'react'
import {UserOutlined,LockOutlined,PhoneOutlined,AppstoreOutlined} from "@ant-design/icons"
import {reg} from "../../utils/validate"
import { withRouter } from 'react-router-dom'
import { $http } from '../../api'
import {mbdata} from '../../mobx/data'

const {TabPane} =Tabs
const {Title}=Typography
const {pwd,phone}=reg
export default function Login({history,location}){
  
    return(
        <div className="login">
            <video 
                className="myvideo" 
                id="myvideo" 
                autoPlay  
                loop  
                playsInline
                muted
                src="https://play.feihuo.com/bizhi/video/new_video/shortVideo/20210827/c49fcf10e6a25f0d143261c50b13188c_wm.mp4"
            ></video>

            <Row className="mybox">
                <Col className="login-box" xs={22} sm={18} md={14} lg={12} xl={6} xxl={4}>
                    <Title level={3}>
                        员工管理系统
                    </Title>
                    <Tabs  defaultActiveKey="1">
                        <TabPane tab="密码登录" key="1">
                            <LoginByPass history={history} location={location} ></LoginByPass>
                        </TabPane>
                        <TabPane tab="手机登录" key="2">
                            <LoginByPhoneRoute></LoginByPhoneRoute>
                        </TabPane>
                    </Tabs>
                </Col>
            </Row>
        </div>
    )
}

const layout = {
    labelCol:{
        span:6,
        offset:1
    },
    wrapperCol:{
        span:16
    }
}

const tailLayout = {
    wrapperCol:{
        span:16,
        offset:7
    }
}
//密码登录
function LoginByPass({history,location}){
    useEffect(()=>{
        var zhuAccount = new URLSearchParams(location.search).get("accout")
        if(zhuAccount){

            form.current.setFieldsValue({
                account:zhuAccount,
                password:""
            })
        }else{
            form.current.setFieldsValue({
                account:localStorage.getItem("accout"),
                password:localStorage.getItem("password"),
            })
        }
    })
    const form=useRef()
    const onFinish=(value)=>{
       
        $http.login(value)
        .then(res=>{
            if(res.code==200){
                sessionStorage.setItem("token",res.token)
                if(value.remember){
                    console.log(res);
                    localStorage.setItem("accout",value.account)
                    localStorage.setItem("password",value.password)
                    mbdata.changeUserInfo(res.result)
                    history.push("/main/")
                }
            }
        })


    }

    const onFailed=()=>{

        message.error("用户信息错误")
    }

    const gotowhere = url=>{
        history.push(url)
    }
    return(
        <div>
            
    <Form
      name="normal_login"
      className="login-form"
      ref={form}
      initialValues={{}}
      onFinish={onFinish}
      onFinishFailed={onFailed}
      {...layout}
    >
      <Form.Item
        label="用户名"
        name="account"
        rules={[{ required: true, message: '用户名不为空' }]}
      >
        <Input prefix={ <UserOutlined className="site-form-item-icon"/>}  placeholder="请输入用户名"/>
      </Form.Item>

      <Form.Item
        label="密  码"
        name="password"
        rules={[
            { required: true, message: 'Please input your password!' },
            { pattern:  pwd, message:"请输入6-16位数字加字母的登录密码"}
        ]}
      >
        <Input.Password prefix={ <LockOutlined className="site-form-item-icon" placeholder="请输入密码"/>}/>
      </Form.Item>

      <Form.Item name="remember" valuePropName="checked" {...tailLayout}>
        <Checkbox>记住密码</Checkbox>
      </Form.Item>


      <Form.Item {...tailLayout}>
        <Button block type="primary" htmlType="submit">
          登录
        </Button>
      </Form.Item>
    </Form>

    <Form.Item {...tailLayout} className="links">
        <span onClick={()=>gotowhere('/register')} style={{color:"#f50"}}>立即注册</span>
        <span onClick={()=>gotowhere('/forgetpass')} style={{color:"#0f0"}}>忘记密码?</span>
    </Form.Item>


        </div>
    )
}


//手机登录
let capt=120
let timer=null
function LoginByPhone({history}){
    const form =useRef()
    const [flag,setFlag]=useState(true)
    const [phonedis,setPhonedis]=useState(false)
    let [count,setCount]=useState(capt)

    useEffect(()=>{
        if(localStorage.getItem("phone")){
            setPhonedis(phone.test(localStorage.getItem("phone")))
        }

        return ()=>{
            clearInterval(timer)
            timer=null
            setFlag(true)
            setCount(capt)
        }
    },[])

    const onFinish=(value)=>{
        $http.checkcaptcha(value)
        .then(res=>{
            if(res.code==200){
                sessionStorage.setItem("token",res.token)
                localStorage.setItem("phone",value.phone)
                mbdata.changeUserInfo(res.result)
                history.push("/main")
            }
        })

    }
    const onFailed=()=>{
        message.error("用户信息有误")
    }
    function initTime(){
        timer=setInterval(()=>{
            if(count>0){
                setCount(--count);
                setFlag(false)
            }else{
                setFlag(true)
                setCount(capt)
                clearInterval(timer)
                timer=null

            }
        },1000)
    }
    const getCaptcha=()=>{
        var phonevalue=form.current.getFieldValue("phone")
        console.log(flag,"flag");
        setCount(--count);
        setFlag(false)
        initTime()
        
        $http.sendcaptcha({
            phone:phonevalue
        }).then(res=>{
            if(res==200){
                
            }
        })
    }

    const thisphone=useRef()
    const changeCheckPhone=()=>{
        var value=form.current.getFieldValue("phone")
        // if(phone.test(value)){
        //     setPhonedis(true)
        // }else{
        //     setPhonedis(false)
        // }
    }
    return(
        <div>
            <Form
      name="normal_login"
      className="login-form"
      ref={form}
      initialValues={{
          phone:localStorage.getItem("phone")
      }}
      onFinish={onFinish}
      onFinishFailed={onFailed}
      {...layout}
    >
      <Form.Item
        label="手机号"
        name="phone"
        rules={[
            { required: true, message: '手机号不为空'  },
            { pattern:phone,message:'请输入正确手机号' }
        ]}
      >
        <Input ref={thisphone} prefix={ <UserOutlined className="site-form-item-icon"/> } onChange={changeCheckPhone}  placeholder="请输入用户手机号"/>
      </Form.Item>

      <Form.Item
        label="验证码"
        name="captcha"
        rules={[
            { required: true, message: '验证码不为空' },
            { pattern: /^\d{4}$/, message:"请输4位数字验证码"}
        ]}
      >
        <Row>
            <Col span={12}>
               <Input  prefix={<AppstoreOutlined className="site-form-item-icon" />}   placeholder="请输入验证码"/> 
            </Col>
            <Col span={11} offset={1}>
                {
                    flag?<Button disabled={phonedis} type="danger" onClick={getCaptcha}>获取验证码</Button>
                    :
                    <Button type="" disabled>剩余{count}s</Button>
                }
            </Col>
        </Row>
      </Form.Item>

      
      <Form.Item {...tailLayout}>
        <Button block type="primary" htmlType="submit">
          登录
        </Button>
      </Form.Item>
    </Form>

    <Form.Item {...tailLayout} className="links">
        <span onClick={()=>history.push('/register')} style={{color:"#f50"}}>立即注册</span>
        <span onClick={()=>history.push('/forgetpass')} style={{color:"#0f0"}}>忘记密码?</span>
    </Form.Item>
        </div>
    )
}

const LoginByPhoneRoute = withRouter(LoginByPhone)